﻿// JScript File

//SM - Server Manager

var SM_PROVIDERPAGE = "ADSData.aspx";
var SM_OK = 50;



//SME - Server Manager Error

var SME_PROVIDERNOTFOUND = 60;
var SME_UNKNOWNERROR = 61;
var SME_NULLDATA = 62;

//SMRID -  Server Manager Request IDentifier

var SMRID_GETASSESSMENT = 52;
var SMRID_GETREPORT = 53;
var SMRID_SENDUSERXML = 54;
var SMRID_DELETEUSERANSWERS = 55;

function ServerManager()
{
    this.errorText = "";
}


//Загружает XmlDOMDocument WebAssessmentItem с сервера в переменную assessmentXml.
//Если ошибка, то возвращает:
/*
    SME_PROVIDERNOTFOUND - страница, которой посылается запрос не найдена
    SME_UNKNOWNERROR - неизвестная ошибка
    SME_NULLDATA - в ответе с сервера не содержится данных
*/
var xmlhttp;
ServerManager.prototype.GetAssessment = function(assessmentXml, args) {
    xmlhttp = CreateXmlHttp();
    
    xmlhttp.open("GET",SM_PROVIDERPAGE,true);    
    xmlhttp.onreadystatechange = HandleRequestStateChange;
    xmlhttp.setRequestHeader("rid",SMRID_GETASSESSMENT);    
    xmlhttp.setRequestHeader("args",args);    
    xmlhttp.setRequestHeader("waitAttemptCount", waitAttemptCount);        
    
    try
    {    
        xmlhttp.send(null);    
    }
    catch (e)
    {
        ShowError(ServerManager_CannotConnectToServerErrorTitle + (e.message == undefined ? e : e.message));
        return SME_PROVIDERNOTFOUND;
    }             
    return SM_OK;
}


function HandleRequestStateChange()
{
    if(xmlhttp.readyState == 4)
    {
        if(xmlhttp.status == 200)
        {
            try
            {
                HandleServerResponse();            
            }
            catch(e)
            {                        
                ShowError(ServerManager_CannotReadServerResponse + (e.message == undefined ? e : e.message));
            }
        }
    }
}
function HandleServerResponse()
{
    var assessmentXml = CreateXmlDOM();   
    
    //document.write(xmlhttp.responseText);
    this.errorText = xmlhttp.responseText; // в случае, если ошибка была на серваке, здесь это понять не сложно - а далее инфа об ошибке будет выводится    
    
    if (this.errorText == "wait")
    {       
        
        waitAttemptCount += 1;
        window.setTimeout("RequestServer();",5000);
        return;
    }       
    
    
    if (this.errorText.indexOf("error") == 0)
    {
        throw this.errorText.substr(6);
    }
    
    if (xmlhttp.responseText == "")
    {    
        throw ServerManager_InvalidTestFormat + "(" + SME_NULLDATA + ")";
    }
        
    try
    {    
        assessmentXml.loadXML(xmlhttp.responseText);               
    }
    catch (e)
    {
        try
        {
            var parser = new DOMParser();                        
            assessmentXml = parser.parseFromString(xmlhttp.responseText,"text/xml");                         
        }
        catch (e2)
        {
            throw ServerManager_UnknownError + "(" + SME_UNKNOWNERROR + "):" + (isNaN(e2.message) ? e2 : e2.message);
        }
    }        
    
    ProcessStart(assessmentXml);  // ответ с сервера пришёл, идём дальше                  
}




ServerManager.prototype.GetReport = function(xmlData)
{   
    xmlhttp = CreateXmlHttp();

    xmlhttp.open("POST",SM_PROVIDERPAGE,true);
    xmlhttp.onreadystatechange = HandleRequestStateChangeOnReportGetting;
    xmlhttp.setRequestHeader("rid", SMRID_GETREPORT);    
    var xml = SerializeXmlNode(xmlData);
    xmlhttp.setRequestHeader('Content-length', xml.length);  

    
    try
    {   
        xmlhttp.send(xml)        
    }
    catch (e)
    {
        ShowError((e.message == undefined ? e : e.message));
    }        

   
    
   
        
    //recieveHTMLData = xmlhttp.responseText;
    
  //  try
  //  {
  //      recieveXmlData.loadXML(xmlhttp.responseText);   
  //  }
  //  catch (e)
  //  {
  //      try
  //      {
  //          var parser = new DOMParser();
  //          recieveXmlData = parser.parseFromString(xmlhttp.responseText,"text/xml");             
  //      }
  //      catch (e2)
  //      {
  //        return SME_UNKNOWNERROR;
  //      }
  //  }
    
    return SM_OK;
}

function HandleRequestStateChangeOnReportGetting()
{
    if(xmlhttp.readyState == 4)
    {
        if(xmlhttp.status == 200)
        {        
            if (xmlhttp.responseText == "")
            {
                return SME_NULLDATA;
            }
            try
            {                          
                appPointer.report.ShowReport(xmlhttp.responseText); 
            }
            catch(e)
            {                           
                ShowError(ServerManager_CannotReadServerResponse + (e.message == undefined ? e : e.message));             
            }
        }
    }
}

var wasAnswerFromServerAboutSaveUserXML = true;

ServerManager.prototype.SaveUserXml = function(xmlData)
{   
    if (!wasAnswerFromServerAboutSaveUserXML)
    {
        networkErrorFasade.innerHTML = ServerManager_NoConnectionError;               
    }


    xmlhttp = CreateXmlHttp();

    xmlhttp.open("POST",SM_PROVIDERPAGE,true);
    xmlhttp.onreadystatechange = HandleRequestStateChangeOnAutoSave;
    xmlhttp.setRequestHeader("rid", SMRID_SENDUSERXML);    
    var xml = SerializeXmlNode(xmlData);
    xmlhttp.setRequestHeader('Content-length', xml.length);  
       

    try
    {
        xmlhttp.send(xml);     
        wasAnswerFromServerAboutSaveUserXML = false;           
    }
    catch (e)
    {
        ShowError((e.message == undefined ? e : e.message));
    }        
    
    return SM_OK;              
}

function HandleRequestStateChangeOnAutoSave()
{
    if(xmlhttp.readyState == 4)
    {
        if(xmlhttp.status == 200)
        {
            try
            {  
                wasAnswerFromServerAboutSaveUserXML = true;  // связь с сервером есть 
                networkErrorFasade.innerHTML = "";               
                            
                if (xmlhttp.responseText != "False")
                    autoSaveTimerPointer.ProcessDone();   
                else                
                    autoSaveTimerPointer.ProcessFailed();
                return;
            }
            catch(e)
            {               
                ShowError(ServerManager_CannotReadServerResponse + (e.message == undefined ? e : e.message));
                autoSaveTimerPointer.ProcessFailed();
            }
        }        
        autoSaveTimerPointer.ProcessFailed();
    }        
}

// если юзер закрыл окно - специально удаляем все его ответы!
ServerManager.prototype.DeleteUserAnswers = function(xmlData)   
{   
    var xmlhttp = CreateXmlHttp();
    
    xmlhttp.open("POST",SM_PROVIDERPAGE,true);    
    xmlhttp.setRequestHeader("rid", SMRID_DELETEUSERANSWERS);    
    var xml = SerializeXmlNode(xmlData);
    xmlhttp.setRequestHeader('Content-length', xml.length);  
       
 
        
    try
    {
        xmlhttp.send(xml);        
        
    }
    catch (e)
    {
        ShowError((e.message == undefined ? e : e.message));
    }        
    
    return SM_OK;              
}
